// app/(tabs)/campaigns.js
import Loading from '@/components/Loading';
import { api } from '@/utils/request/Api';
// 由于模块 "@/interface/interface" 未导出 "Emails"，暂时移除该导入
// 若后续需要使用，需确保在对应模块中正确导出该类型
import { Email,Template } from '@/interface/interface';
import { Ionicons } from '@expo/vector-icons';
import { router, useLocalSearchParams } from 'expo-router';
import React, { useEffect, useRef, useState } from 'react';
import { Alert,KeyboardAvoidingView, ActivityIndicator,FlatList,RefreshControl, Image, Modal, Platform, ScrollView, StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { RichEditor, RichToolbar, actions } from "react-native-pell-rich-editor";
let page = 1;
export default function CampaignsScreen() {
  let { crawlId } = useLocalSearchParams();
  const [subject, setSubject] = useState('');
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [emails, setEmails] = useState<Email[]>([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [templates, setTemplates] = useState<Template[]>([]);
  const [lastpage,setLastpage] = useState(1);
  const richText = useRef<RichEditor>(null);
  const [refreshing, setRefreshing] = useState(false);
// 頁面挂載階段
  useEffect(() => { 
    setLoading(true)
    api.get("email/items",{params:{crawl_id:crawlId,status:1}}).then((res) => {
      setLoading(false);
      if(res && res.code == 1){
        setEmails(res.data as Email[]);
        setLastpage(res.data.last_page);
      }
    })
    // 获取邮件模板
    setTemplates([]);
    fetchTemplate();
  }, [crawlId])
  // 发送邮件的辅助函数
  const sendEmail = (emailContent: string) => {
    if(loading){return false;}
    setLoading(true);
    api.post("email/send",{
      data:{
        crawl_id:crawlId,
        subject,
        content: emailContent,
        emails:emails.map((item:any) =>
           item.email)
      }
    }).then((res) => {
      setLoading(false)
      if(res.code == 0){
        Alert.alert('Tip',`Email send failed`,[
          {text:"Confirm"}
        ]);
        return false;
      }
      setContent('');
      setSubject('')
      if(richText.current){
        richText.current.setContentHTML('');
      }
      if(Platform.OS === 'web'){
          alert(`Sending to ${emails.length} recipients`);
          router.push(`/home`);
      }else{
         Alert.alert('Tip',`Sending to ${emails.length} recipients`,[
          {
              text: "ok",
              onPress: () => {
                
                // // 添加空值检查以避免 Cannot read property 'count' of null 错误
                if(res && res.data && res.data.count > 0){
                  router.push(`/home`);
                } else {
                  // 处理数据不存在的情况
                  router.push(`/home`);
                }
              }
            }
         ])
      }
    }).catch((err) => {
      setLoading(false);
      Alert.alert('Tip',`Network request failed`,[
        {text:"Confirm"}
      ]);
    })
  }
  const handleLoadMore = () => {
    if(page > 0 && page < lastpage){
      page++;
      fetchTemplate();
    }
  }
  // 获取邮件模板
  function fetchTemplate(){
    setRefreshing(true);
    api.get('template/list', { params: { page: page } }).then((res) => {
      setRefreshing(false);
      if(res.code == 1){
         setTemplates(prev => [...prev, ...(res.data.data as Template[])]);
         setLastpage(res.data.last_page); 
      }
    }).catch(() => {setRefreshing(false);})
  }
  const setTemplateContent = (item:any) => {
    setContent(item.content);
    setModalVisible(false);
    if(richText.current){
      richText.current.setContentHTML(item.content);
    }
  }

  // 监听 content 状态变化，同步到 RichEditor
  useEffect(() => {
    
  }, [content])
  const onRefresh = () => {
    setTemplates([])
    page = 1
    setLastpage(1);
    
    fetchTemplate();
  }
  // 弄

  const handleSend = () => {
    if (!subject || !content) {
      Alert.alert('Error', 'Please enter subject and content');
      return;
    }
    sendEmail(content);
  };
  const clearContent = () => {
    Alert.alert('Tip',`Confirm clean ?`,[
      {
        text:"clean",
      },
      {
        text: "confirm",
        onPress: () => {
          if (richText.current) {
            setContent('');
            richText.current.setContentHTML('');
          }
        }
      }
    ])
    
  };

  return (
    <KeyboardAvoidingView behavior={Platform.OS == "ios" ? "padding" : "height"}>
    <ScrollView contentContainerStyle={styles.container}>
      <Text style={styles.title}>Email Campaigns</Text>
      <Text style={styles.subtitle}>Create Campaign</Text>
      <Text style={styles.description}>Send an email campaign to {emails.length} recipients</Text>

      <Text style={styles.label}>Email Subject</Text>
      <View style={styles.inputBox}>
        <Ionicons name="mail-outline" size={18} color="#999" style={{ marginRight: 8 }} />
        <TextInput
          style={styles.input}
          placeholder="Enter the subject of your email"
          value={subject}
          onChangeText={setSubject}
        />
      </View>
      <Text style={styles.label}>Email Content </Text>
      
      <View>
        <Text style={styles.description}>Choose your email
          <Text style={{color:'#3B82F6'}} onPress={() => setModalVisible(true)}> template</Text>
        </Text>
      </View>
      <View style={styles.editorContainer}>
      <ScrollView  style={{borderColor:"#eee",borderWidth:0,borderRadius:10,margin:1,flex:1,height:300}}>
          <RichEditor
            initialHeight={300}
            ref={richText}
            style={styles.editor}
            initialContentHTML={content}
            onChange={(html) => setContent(html)}
          />
          
      </ScrollView>
      <RichToolbar
            getEditor={() => richText.current}
            RichTextToolbar={true}
            iconSize={15}
            style={styles.toolbar}
            actions={[ 
                'clearContent',
                actions.setBold,
                actions.setItalic,
                actions.setUnderline,
                actions.insertBulletsList,
                actions.insertOrderedList,
                actions.insertLink,
                actions.setStrikethrough,
                actions.removeFormat,
                actions.undo,
                actions.redo,
                // actions.insertImage,
                // actions.code,
                
              ]}
              iconMap={{ 
                'clearContent': () => (
                  <Ionicons name="trash-outline" size={15} color="#f43f5e" />
                )
               }}
              clearContent={() => clearContent()}
        />
      </View>
      <Text style={styles.label}>Recipients ({emails.length})</Text>
      <View style={styles.recipientBox}>
        {emails.map(email => (
          <Text key={email.id} style={styles.recipient}>{email.email}</Text>
        ))}
      </View>

      <TouchableOpacity style={ loading ? styles.senddisbaleBtn : styles.sendBtn } onPress={handleSend} disabled={loading}>
        <Text style={styles.sendText}>
           📤&nbsp;
           
           Send Campaign</Text>
      </TouchableOpacity>
      {loading && <Loading />}
    </ScrollView>
      <Modal animationType="slide" transparent={true} visible={modalVisible}>
         <View style={styles.modelConHtainer}> 
          <View style={styles.modelHeaderBar}>
            <TouchableOpacity onPress={() => setModalVisible(false)}>
              <Text style={styles.modelBackText}>←</Text>
            </TouchableOpacity>
            <Text style={styles.modelHeaderTitle}>Template</Text>
            <View style={{ width: 24 }} /> 
          </View>
          <FlatList
            onEndReached={handleLoadMore}
            onEndReachedThreshold={15}
            refreshControl={<RefreshControl refreshing={refreshing} onRefresh={() => onRefresh()}/>}
            data={templates}
            keyExtractor={(item:any) => item.key}
            contentContainerStyle={{ paddingBottom: 10 }}
            renderItem={({ item }) => (
              <TouchableOpacity onPress={() => setTemplateContent(item)} style={styles.modelCard}>
                <View style={styles.modelItemImage}>
                    <Image source={{ uri: item.thumb }} style={styles.modelImage} />
                </View>
                <View style={styles.modelItemContent}>
                    <Text style={styles.modelName} numberOfLines={2} ellipsizeMode="tail">{item.name}</Text>
                    <Text style={styles.modelDesc} numberOfLines={3} ellipsizeMode="tail">{item.desc}</Text>
                </View>
              </TouchableOpacity>
            )}
          />
         </View>
      </Modal>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: { padding: 20, backgroundColor: '#fff' },
  title: { fontSize: 22, fontWeight: '600', marginTop: 20, textAlign: 'center' },
  subtitle: { fontSize: 18, fontWeight: '600', marginTop: 30 },
  description: { fontSize: 14, color: '#666', marginBottom: 20 },
  label: { fontWeight: '600', marginTop: 20, marginBottom: 8 },
  inputBox: {
    flexDirection: 'row', alignItems: 'center', backgroundColor: '#f3f4f6',
    paddingHorizontal: 12, borderRadius: 10, height: 48
  },
  input: { flex: 1, fontSize: 14 },
  textarea: {
    backgroundColor: '#f9fafb', borderRadius: 10, padding: 12,
    fontSize: 14, textAlignVertical: 'top'
  },
  recipientBox: {
    backgroundColor: '#f3f4f6', padding: 12, borderRadius: 8, marginBottom: 30
  },
  recipient: { fontSize: 14, paddingVertical: 2, color: '#333' },
  sendBtn: {
    backgroundColor: '#3B82F6', padding: 14, borderRadius: 12,
    alignItems: 'center', justifyContent: 'center', marginBottom: 40
  },
  senddisbaleBtn:{
    backgroundColor: '#88b6ffff', padding: 14, borderRadius: 12,
    alignItems: 'center', justifyContent: 'center', marginBottom: 40
  },
  sendText: { color: '#fff', fontSize: 18, fontWeight: '600' },
  modelConHtainer: {
    flex: 1,
    backgroundColor: '#fff',
    paddingTop: 20,
    paddingHorizontal: 16,
  },
  modelHeaderBar: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingBottom: 10,
    paddingTop: 15,
    borderBottomWidth: 1,
    borderBottomColor: '#eee',
    marginBottom: 5,
  },
  modelBackText: {
    fontSize: 32,
    fontWeight:900,
    color: '#333',
    marginTop:20,
  },
  modelHeaderTitle: {
    fontSize: 18,
    fontWeight: 600,
    color: '#111',
    paddingTop: 15,
  },
  modelCard: {
      backgroundColor: '#f9f9f9',
      borderRadius: 12,
      padding: 12,
      width: '100%',
      marginBottom: 16,
      shadowColor: '#000',
      shadowOffset: { width: 0, height: 2 },
      shadowOpacity: 0.05,
      shadowRadius: 4,
      elevation: 2,
      flexDirection: 'row',
      justifyContent: 'space-between',
    },
  modelImage: {
    width: '100%',
    height: 100,
    
  },
  modelName: {
    color: '#333',
    fontSize: 16,
    fontWeight: '500',
    marginBottom: 4,
  },
  modelDesc: {
    color: '#777',
    fontSize: 14,
  },
  modelItemImage:{
    flex:2,
  },
  modelItemContent:{
    width: '50%',
    flex:3,
    paddingLeft:10,
    paddingTop:0
  },
  editorContainer: {
    borderWidth: 1,
    borderColor: '#f3f3f3',
    borderRadius: 8,
    overflow: 'hidden',
    marginBottom: 10,
  },
  toolbar: {
    backgroundColor: '#f9f9f9',
    borderBottomColor: '#ddd',
  },
  editor: {
    minHeight: 600,
    padding: 5,
    backgroundColor: '#fff',
  },
  debugBtn: {
    backgroundColor: '#6c757d',
    padding: 10,
    borderRadius: 8,
    alignItems: 'center',
    marginTop: 10,
    marginBottom: 10,
  },
  debugText: {
    color: '#fff',
    fontWeight: 'bold',
  },
});